﻿using System;
using System.Collections.Generic;
using System.Data;
using Elentok.Common.Collections;

namespace Elentok.Common.Helpers
{
  /// <summary>
  /// Database-related extension methods
  /// </summary>
  public static class DBHelper
  {
    /// <summary>
    /// Returns the column indexes by their name
    /// </summary>
    /// <param name="reader"></param>
    /// <returns></returns>
    public static IReadOnlyDictionary<string, int> GetColumnIndexesByName(this IDataRecord reader)
    {
      Dictionary<string, int> columnIndexesByName = new Dictionary<string, int>();
      for (int i = 0; i < reader.FieldCount; i++)
      {
        columnIndexesByName.Add(reader.GetName(i).ToUpperInvariant(), i);
      }
      return columnIndexesByName.AsReadOnly();
    }

    /// <summary>
    /// Adds a parameter to a DB command
    /// </summary>
    /// <param name="command"></param>
    /// <param name="parameterName"></param>
    /// <param name="value"></param>
    /// <param name="dbType"></param>
    /// <returns></returns>
    public static IDbDataParameter AddParameter(this IDbCommand command, string parameterName, object value, DbType dbType)
    {
      IDbDataParameter parameter = command.CreateParameter();
      parameter.ParameterName = parameterName;
      if (value == null)
        parameter.Value = DBNull.Value;
      else
        parameter.Value = value;
      parameter.DbType = dbType;
      command.Parameters.Add(parameter);
      return parameter;
    }

  }
}
